<template>
  <div class="user-listdialog">
    <el-dialog
      :title="text_Tit"
      :visible.sync="newModalToggle"
      width="50%"
      :before-close="userClose"
    >
      <div class="user-content">
        <el-tabs v-model="tabToggle" type="card">
          <el-tab-pane label="登录信息" name="first">
            <el-form
              :inline="true"
              class="demo-form-inline"
              :model="userForm.uUser"
              ref="userForm"
              :rules="rulesUser"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-row :gutter="20" style="margin: 0 0 10px 0">
                    <el-col :span="7" style="padding: 0">
                      <span class="red">*</span>
                      <span>昵称：</span>
                    </el-col>
                    <el-col :span="17" style="padding: 0">
                      <el-form-item prop="nickname">
                        <el-input
                          v-model.trim="userForm.uUser.nickname"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="12">
                  <el-row :gutter="20" style="margin: 0 0 10px 0">
                    <el-col :span="7" style="padding: 0">
                      <span class="red">*</span>
                      <span>账号：</span>
                    </el-col>
                    <el-col :span="17" style="padding: 0">
                      <el-form-item prop="username">
                        <el-input
                          v-model.trim="userForm.uUser.username"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-row :gutter="20" style="margin: 0 0 10px 0">
                    <el-col :span="7" style="padding: 0">
                      <span class="red">*</span>
                      <span>密码：</span>
                    </el-col>
                    <el-col :span="17" style="padding: 0">
                      <el-form-item prop="password">
                        <el-input
                          type="password"
                          v-model.trim="userForm.uUser.password"
                          @blur="clearpswValidate"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>

                <el-col :span="12">
                  <el-row :gutter="20" style="margin: 0 0 10px 0">
                    <el-col :span="7" style="padding: 0">
                      <span class="red">*</span>
                      <span>角色：</span>
                    </el-col>
                    <el-col :span="17" style="padding: 0">
                      <el-form-item prop="roleId">
                        <el-select
                          v-model="userForm.uUser.roleId"
                          placeholder="请选择"
                          @change="selectRole"
                        >
                          <el-option
                            v-for="(item, index) in typeoptions"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-row :gutter="20" style="margin: 0 0 10px 0">
                    <el-col :span="7" style="padding: 0">
                      <span class="red">*</span>
                      <span>行政区划：</span>
                    </el-col>
                    <el-col :span="17" style="padding: 0">
                      <el-form-item prop="regionName">
                        <el-input
                          v-model="userForm.uUser.regionName"
                          placeholder="请选择"
                          @focus="modelStatus('xzqh')"
                          readonly
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <!-- <el-col :span="12">
                  <el-row :gutter="20" style="margin:0 0 10px 0">
                    <el-col :span="7" style="padding:0">
                      <span class="red">&nbsp;&nbsp;</span>
                      <span>部门：</span>
                    </el-col>
                    <el-col :span="17" style="padding:0">
                      <el-form-item>
                        <el-input
                          v-model="userForm.uUser.bmbm"
                          placeholder="请选择"
                          @focus="modelStatus('bm')"
                          clearable
                          @clear="clearBm"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>-->
              </el-row>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="userbtn_save">保 存</el-button>
        <el-button @click="btn_cancel">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 行政证区划弹框 -->
    <!-- default-expand-all -->
    <el-dialog
      :title="model_Tit"
      :visible.sync="xzqh_model"
      width="50%"
      :before-close="xzqhClose"
    >
      <el-scrollbar wrapClass="scrollbar-wrapper">
        <el-tree
          :data="xzqh_data"
          @node-click="nodeClick"
          :expand-on-click-node="false"
          :highlight-current="true"
          :props="defaultProps"
        ></el-tree>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="xzqh_save">保 存</el-button> -->
        <el-button @click="xzqhClose">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 部门弹框 -->
    <el-dialog
      :title="model_Tit"
      :visible.sync="bm_model"
      width="50%"
      :before-close="xzqhClose"
    >
      <el-tree
        :data="bm_data"
        @node-click="bmnodeClick"
        default-expand-all
        :expand-on-click-node="false"
        :highlight-current="true"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="xzqh_save">保 存</el-button> -->
        <el-button @click="xzqhClose">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDicTab } from "@/utils/config"; // doCreate,
import { userAdd, userEdit } from "@/api/user"; // , userSearch
import { roleSearch } from "@/api/role";
import { validPassword } from "@/utils/validate";
import { treeQuery } from "@/api/administrative";
import { treeQueryBm } from "@/api/department";
import { getPublicKey } from "@/api/login";
import JSEncrypt from "jsencrypt";
// import { debug } from 'util'
export default {
  data() {
    const PassWord = (rule, value, callback) => {
      if (!validPassword(value) && !this.userForm.uUser.id) {
        callback(new Error("密码由6-20字母和数字组成"));
      } else {
        callback();
      }
    };
    return {
      newModalToggle: false,
      xzqh_model: false,
      bm_model: false,
      tabToggle: "",
      text_Tit: "",
      xzqh_data: [],
      bm_data: [],
      userXzqh: "",
      bmbm: "",
      xzqh: "110100",
      model_Tit: "",
      typeoptions: [],
      userForm: {
        uUser: {
          nickname: "",
          username: "",
          password: "",
          roleId: "",
          roleName: "",
          userstatus: 0,
          yxkssj: "",
          yxjzsj: "",
          mmyxsj: "",
          xzqh: "110100",
          regionCode: "",
          regionName: "",
          createUser: this.$store.state.user.user.username
          // bmbm: ""
        },
        uUserInfo: {
          zc: "",
          lx: "",
          sstd: "",
          tel: ""
        }
      },
      rulesUser: {
        nickname: [{ required: true, message: "不能为空" }],
        username: [{ required: true, message: "不能为空" }],
        // xzqhmc: [{ required: true, message: "不能为空" }],
        // bmbm: [{ required: true, message: "不能为空" }],
        password: [
          {
            required: true,
            validator: PassWord,
            trigger: "blur"
          }
        ],
        roleId: [{ required: true, message: "不能为空" }]
      },
      defaultProps: {
        children: "children",
        label: "name"
      }
    };
  },
  props: {
    newModal: Boolean,
    activeTab: {
      default: "first"
    },
    textTit: {
      default: ""
    },
    userData: {
      default: () => {}
    }
  },
  methods: {
    selectRole(val) {
      let dicMap = window.sessionStorage;
      let data = JSON.parse(dicMap.getItem("role"));
      data.forEach((el, index) => {
        if (val === el.id) {
          this.userForm.uUser.roleName = el.roleName;
        }
      });
      console.log(this.userForm.uUser);
    },
    clearpswValidate() {
      // 失焦并且是修改信息时去除password校验
      if (this.userForm.uUser.id) {
        // this.$refs["userForm"].clearValidate("password");
        this.rulesUser.password[0].required = false;
      }
    },
    clearBm() {
      this.userForm.uUser.bmbm = "";
      this.bmbm = "";
    },
    remarkDic(row) {
      return getDicTab("remark", row);
    },
    remarkHq(row) {
      // eslint-disable-next-line eqeqeq
      if (row.search("_") != -1) {
        return row.split("_")[0];
      }
      return row;
    },
    // 查询部门树
    bmData() {
      treeQueryBm({ xzqh: this.xzqh }).then((res) => {
        let data = res.data;
        this.bm_model = true;
        if (data.success) {
          this.bm_data = data.data;
        }
      });
    },
    modelStatus(data) {
      let _this = this;
      if (data) {
        // eslint-disable-next-line eqeqeq
        if (data == "xzqh") {
          this.model_Tit = "行政区划";
          treeQuery({ xzqh: this.userXzqh }).then((res) => {
            let data = res.data;
            this.xzqh_model = true;
            if (data.success) {
              _this.xzqh_data = [data.data];
              // _this.$refs.multipleTable.toggleRowSelection(_this.xzqh,true);
            }
          });
          // eslint-disable-next-line eqeqeq
        } else if (data == "bm") {
          if (this.userForm.uUser.xzqh) {
            this.model_Tit = "部门编码";
            this.bmData();
          } else {
            this.$message({
              type: "warning",
              message: "请返回选择行政区划"
            });
            return false;
          }
        }
      }
    },
    xzqhClose() {
      this.xzqh_model = false;
      this.bm_model = false;
    },
    btn_cancel() {
      this.newModalToggle = false;
      this.$emit("newToggle", this.newModalToggle);
    },
    userClose() {
      this.btn_cancel();
    },
    nodeClick(data) {
      this.xzqh = data.code;
      this.userForm.uUser.regionName = data.name;
      // this.userForm.uUser.bmbm = "";
      this.xzqh_model = false;
      this.bm_model = false;
    },
    bmnodeClick(data) {
      this.bmbm = data.bm;
      this.userForm.uUser.bmbm = data.name;
      this.xzqh_model = false;
      this.bm_model = false;
    },
    addUser(url, obj, ymmErr) {
      let _this = this;
      userAdd(url, obj).then((res) => {
        let data = res.data;
        if (data.success) {
          delete _this.userForm.uUser.id;
          _this.btn_cancel();
          _this.bmbm = "";
          _this.xzqh = "";
          _this.$message({
            message: data.msg,
            type: "success"
          });
          _this.$emit("addevent", Math.random());
        } else {
          _this.userForm.uUser.password = ymmErr;
          _this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    userbtn_save() {
      let _this = this;
      let url = "";
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          // _this.userForm.uUser.regionCode = this.xzqh;
          // _this.userForm.uUser.regionName = "市辖区";
          // this.userForm.uUser.bmbm = this.bmbm;
          _this.userForm.uUser.cjr = _this.$store.state.user.nickname;
          if (!_this.userForm.uUser.id) {
            url = "add";
            getPublicKey().then((res) => {
              let data = res.data;
              var publicKey = data.data;
              // eslint-disable-next-line no-undef
              let encrypt = new JSEncrypt();
              encrypt.setPublicKey(publicKey);
              _this.userForm.uUser.password = encrypt.encrypt(
                _this.userForm.uUser.password
              );
              let ymmErr = _this.userForm.uUser.password;
              _this.addUser(url, _this.userForm.uUser, ymmErr);
            });
          } else {
            url = "edit";
            _this.$refs["userForm"].clearValidate("password");
            _this.rulesUser.password[0].required = false;
            _this.addUser(url, _this.userForm.uUser);
          }
          // if (
          //   _this.remarkDic(_this.userForm.uUser.rId).indexOf("czy_") != "-1" ||
          //   _this.remarkDic(_this.userForm.uUser.rId).indexOf("gly_bm_") !=
          //     "-1" ||
          //   _this.remarkDic(_this.userForm.uUser.rId).indexOf("ld_bm") != "-1"
          // ) {
          //   if (_this.bmbm == "") {
          //     _this.$message({
          //       message: "请选择部门~",
          //       type: "error"
          //     });
          //     _this.userForm.uUser.xzqh = getDicTab("xzqh", this.xzqh);
          //     return;
          //   } else {
          //     userAdd(_this.userForm).then(res => {
          //       let data = res.data;
          //       if (data.success) {
          //         delete _this.userForm.uUser.id;
          //         _this.btn_cancel();
          //         _this.bmbm = "";
          //         _this.xzqh = "";
          //         _this.$message({
          //           message: data.msg,
          //           type: "success"
          //         });
          //         _this.$emit("addevent", Math.random());
          //       } else {
          //         _this.$message({
          //           message: data.msg,
          //           type: "error"
          //         });
          //       }
          //     });
          //   }
          // } else {
          //   userAdd(_this.userForm).then(res => {
          //     let data = res.data;
          //     if (data.success) {
          //       delete _this.userForm.uUser.id;
          //       _this.btn_cancel();
          //       _this.bmbm = "";
          //       _this.xzqh = "";
          //       _this.$message({
          //         message: data.msg,
          //         type: "success"
          //       });
          //       _this.$emit("addevent", Math.random());
          //     } else {
          //       _this.$message({
          //         message: data.msg,
          //         type: "error"
          //       });
          //     }
          //   });
          // }
        }
      });
    },
    // 解析用户角色
    userRole() {
      let dicMap = window.sessionStorage;
      roleSearch().then((res) => {
        let data = res.data;
        if (data.success) {
          this.typeoptions = data.data.map((i) => {
            i.label = i.roleName;
            i.value = i.id;
            return i;
          });
          dicMap.setItem("role", JSON.stringify(data.data));
          let remarkArr = [];
          data.data.map((i) => {
            remarkArr.push({
              label: i.remark,
              value: i.id
            });
          });
          dicMap.setItem("remark", JSON.stringify(remarkArr));
        }
      });
    }
  },
  watch: {
    "userForm.uUser.password"(newVal, oldVal) {
      if ((newVal, oldVal)) {
        this.$refs["userForm"].clearValidate("password");
      }
    },

    newModal(val) {
      this.newModalToggle = val;
      this.tabToggle = this.activeTab;
      this.text_Tit = this.textTit;
      if (this.$refs.userForm) {
        this.$refs.userForm.resetFields();
      }
    },
    userData(val) {
      // eslint-disable-next-line eqeqeq
      if (!(JSON.stringify(val) == "{}")) {
        // this.bmbm = val.uUser.bmbm;
        // let obj = Object.assign({}, val.uUser);
        // obj.xzqh = getDicTab("xzqh", val.uUser.xzqh);
        // if (val.uUser.bmbm) {
        //   obj.bmbm = getDicTab("bmbm", val.uUser.xzqh + "-" + val.uUser.bmbm);
        // }
        this.xzqh = val.regionCode;
        this.userForm.uUser.regionName = val.regionName;
        this.userForm.uUser.roleId = val.roleId;
        this.userForm.uUser = Object.assign(this.userForm.uUser, val);

        console.log(this.userForm.uUser);
      } else {
        if (this.$refs.userForm) {
          this.$refs.userForm.resetFields();
        }
        this.userForm.uUser = {
          nickname: "",
          username: "",
          password: "",
          roleId: "",
          userstatus: "",
          yxkssj: "",
          yxjzsj: "",
          mmyxsj: "",
          xzqh: "",
          // 测试赋值,正常弹窗选择应设为空
          regionCode: "110100",
          regionName: "市辖区"
        };
      }
    }
  },
  mounted() {
    this.userRole();
    // this.userXzqh = this.$store.state.user.user.uUser.xzqh;
    this.userXzqh = "110100";
    if (this.userForm.uUser.id) {
      this.$refs["userForm"].clearValidate("password");
    }
  }
};
</script>
<style lang="scss" scoped>
.user-listdialog {
  .user-content {
    border-bottom: 1px dashed #ccc;
    padding-bottom: 20px;
  }
}
</style>

<style lang="scss">
.user-listdialog {
  .el-dialog__header {
    background: #00b09e;
    .el-dialog__title {
      color: #fff;
    }
  }
  .el-dialog__body {
    padding: 20px 20px 0 20px;
  }
  .user-content {
    .el-input__inner {
      border-radius: 0;
    }
    .el-select {
      width: 100%;
    }
    .el-date-editor {
      width: 100%;
    }
    .el-button {
      height: 40px;
      margin: 0 5px;
    }
  }
  .el-dialog__footer {
    text-align: center;
  }
  .el-form-item {
    width: 100%;
    margin-bottom: 0;
    & > div {
      width: 100%;
    }
  }
}
</style>
